package cn.tianya.irock.core;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.tianya.irock.view.MessagePage;

public class ApplicationServlet extends HttpServlet {
	private static Logger logger = Logger.getLogger(ApplicationServlet.class);
	
	protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		HttpRequest request = null;
		HttpResponse response = null;
		HttpContext context = null;
		FormsAuthenticationModule authModule = null;
		
		request = new HttpRequest(req);
		response = new HttpResponse(resp);

		context = new HttpContext(request, response);
					
		authModule = new FormsAuthenticationModule(context);
		authModule.beginAuthenticateRequest();
	}
	
	protected Writer handlePage(HttpContext context, Page page) throws Exception {
		Writer out = null;
		Configuration config = null;
		
		config = Configuration.config();
		page.preInit(context);
		page.initial();
		page.preRender();
		String encoding = config.getProperty(Configuration.ENCODING);
		
		if (context.response().getRedirectUrl() == null) {
			String contentType = context.response().getContentType();
			if (contentType == null) {
				contentType = "text/html; charset=" + encoding;
			}
			context.response().setContentType(contentType);
			if (!context.isCustomContent()) {
				out = new BufferedWriter(new OutputStreamWriter(context.response().getOutputStream(), encoding));
				page.render(out);
				out.flush();
			}
		}
		return out;
	}
	
	protected Writer handleErrPage(HttpContext context, Exception ex) {
		Writer out = null;
		try {
			MessagePage page = new MessagePage();
			page.setException(ex);
			out = this.handlePage(context, page);
		} catch (Exception e) {
			logger.error("Exception", ex);
			//context.response().setRedirect("/apps/sys/error.jsp");
		}
		return out;
	}
}
